//
//  NewFeaTureViewController.swift
//  weibo
//
//  Created by Qing on 2017/6/8.
//  Copyright © 2017年 成哥哥. All rights reserved.
//

import UIKit
import SnapKit

private let WBNewFeaTrueCellID = "Cell"

/// cell的页数
private let WBNewFeaTrueCellCount = 3


class NewFeaTureViewController: UICollectionViewController {
    
    //实例化cell布局。
    let layout = UICollectionViewFlowLayout()
    
    
//    构造函数
    init() {
        
        //cell的大小
        layout.itemSize = UIScreen.main.bounds.size
        //cell的滚动方向
        layout.scrollDirection = .horizontal
        //cell的间距
        layout.minimumLineSpacing = 0
        
//
        
        
//        调用父类的初始化方法
        super.init(collectionViewLayout: layout)
        
        //滚页一半是否可以停止
        collectionView?.isPagingEnabled = true
        
        //到首尾页，滑动是否反弹显示。
        collectionView?.bounces = false
        
        //翻页滚动条是否显示。
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.backgroundColor = UIColor.blue
//        预计是否开启
//        collectionView?.isPrefetchingEnabled = false
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        注册cell
        self.collectionView!.register(NewFeature.self, forCellWithReuseIdentifier: WBNewFeaTrueCellID)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return WBNewFeaTrueCellCount
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WBNewFeaTrueCellID, for: indexPath) as! NewFeature
    
        // Configure the cell
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.brown : UIColor.blue
        
        cell.imageIndex = indexPath.item
        
    
        return cell
    }
    

    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        /*
         contentSize是scrollview可以滚动的区域，比如frame = (0 ,0 ,320 ,480) contentSize = (320 ,960)，代表你的scrollview可以上下滚动，滚动区域为frame大小的两倍。
         contentOffset是scrollview当前显示区域顶点相对于frame顶点的偏移量，比如上个例子你拉到最下面，contentoffset就是(0 ,480)，也就是y偏移了480
         contentInset是scrollview的contentview的顶点相对于scrollview的位置，例如你的contentInset = (0 ,100)，那么你的contentview就是从scrollview的(0 ,100)开始显示
        */
        //计算翻到第几页
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page != WBNewFeaTrueCellCount - 1 {
            return
        }
        
        //代理新特性Cell
        let cell = collectionView?.cellForItem(at: IndexPath(item: page, section: 0)) as! NewFeature
        
        //是否隐藏按钮
        cell.startButton.isHidden = false
        //显示动画
        cell.showButtonAnim()
        
    }
}

//MARK: - 新特性Cell相关
extension NewFeaTureViewController {


    /// 新特性Cell
    class NewFeature: UICollectionViewCell {
        
        /// 图像属性，属性观察器：didSet。
        fileprivate var imageIndex: Int = 0 {
        
            didSet {
            
                iconView.image = UIImage(named: "NewTeaTrue_flower_\(imageIndex + 1)")
            }
            
        }
        
//        重写指定构造函数
        override init(frame: CGRect) {
//          frame的大小由layout.item 指定的。
            super.init(frame: frame)
            setupUI()
            startButton.isHidden = true

            //监听事件
            startButton.addTarget(self, action: "didIconBut", for: UIControlEvents.touchUpInside)
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        /// 添加可以显示image的视图控件到item上。
        fileprivate func setupUI() {
        
//            1.添加控件
            addSubview(iconView)
            addSubview(startButton)
            
//            2.控件约束
            startButton.snp.makeConstraints { (make) in
                make.centerX.equalTo(self.snp.centerX)
                make.centerY.equalTo(self.snp.centerY).multipliedBy(1.7)
            }
            iconView.frame = bounds
            
            
        }
        
        
        /// 显示开始体验动画
        fileprivate func showButtonAnim(){
            
            //开始先把button按钮缩小为0 看不到。
            startButton.transform = __CGAffineTransformMake(0, 0, 0, 0, 0, 0)
            //按钮开始的时候禁止用户交互，等动画完成后才可以交互
            startButton.isUserInteractionEnabled = false
            
            UIView.animate(withDuration: 2,                     //动画时长
                           delay: 0,                            //延时时间
                           usingSpringWithDamping: 0.6,         //弹力系数，0~1 超小越弹
                           initialSpringVelocity: 5,            //初始速度，模拟重力加速度
                           options: [],                         //动画选项
                           animations: {                        //执行动画
                self.startButton.transform = CGAffineTransform.identity
            }) { (_) in                                         //动画完成后的操作
                
                //完成动画，开启交互
                self.startButton.isUserInteractionEnabled = true
                
                
            }
        }
        
//MARK: - 懒加载控件
        fileprivate lazy var iconView: UIImageView = UIImageView()
        fileprivate lazy var startButton: UIButton = UIButton(type: UIButtonType.system, image: "", title: "开始体验", stated:
            UIControlState.normal)
        
        //监听动作
        func didIconBut() {
            print("开始体验")
//            NotificationCenter.default.post(name: "WBSwiftRootViewController", object: "开始体验")
              NotificationCenter.default.post(name: NSNotification.Name.init("WBSwiftRootViewController"), object: nil)
            
        }
    }
}
